<?php
namespace Admin\Controller;

use Common\Controller\BackendController;

class BannerController extends BackendController
{
    public function index()
    {
        $model = D('Banner');
        $banners = $model->select();
        $this->assign('banners',$banners);
        $this->display();
    }

    public function store()
    {
       if(IS_POST) {
           $model = D('Banner');
           if($_FILES['logo']['error'] == 0) {
               $img = $this->getFile($_FILES);
           }
           $data['img'] = $img;
           $data['url'] = trim($_POST['url']);

           $info = $model->add($data);
           if ($info) {
               $this->success('操作成功！', U('index'));
           } else {
               $this->success('操作失败！', U('index'));
           }
       }
    }

    public function update()
    {
        $model = D('Banner');
        if(IS_POST) {
            $show = I('post.show');
            if($show == 1) {
                $where['is_show'] = 0;
            } else {
                $where['is_show'] = 1;
            }
            $id = $model->where(['id'=>I('post.id')])->save($where);
            if ($id) {
                $this->jsonReturn([
                    'msg' => 'success',
                    'state' => 200
                ]);
            } else {
                $this->jsonReturn([
                    'msg' => 'error',
                    'state' => 201
                ]);
            }
        }

    }

    public function destroy()
    {
        $model = D('Banner');
        $id = I('post.id');
        $info = $model->where(['id'=>$id])->delete();
        $this->jsonReturn([
            'msg' => 'success',
            'state' => 200
        ]);
    }

    public function edit()
    {
        $model = D('Banner');
        $id = I('get.id');
        if(IS_POST){
            if ($_FILES['logo']['error'] == 0) {
                $img = $this->getFile($_FILES);
                $data['img'] = $img;
            }
            $url = I('post.url');
            $data['url'] = $url;
            $info = $model->where(['id'=>I('post.id')])->save($data);
            if ($info) {
                $this->success('操作成功！', U('index'));
            } else {
                $this->success('操作失败！', U('index'));
            }
        }
        $banner = $model->find($id);
        $this->assign('banner',$banner);
        $this->display();

    }

    public function getFile($file)
    {
        $dir = date('ym/d/');
        $result = $this->_upload($file['logo'], 'banner/' . $dir);
        $savename = 'data/upload/banner/' .$dir . $result['info'][0]['savename'];
        return $savename;
    }

}